/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sd.chat;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

/**
 *
 * @author Old
 */
public class picUtils {
    
    public static BufferedImage resizePic(BufferedImage bufImage, int maxW, int maxH){
        int initWi = bufImage.getWidth();
        int initHe = bufImage.getHeight();
        System.out.println("initWi:" + initWi + " initHe:"+initHe);

            int maxWi = maxW;
            int maxHe = maxH;
            int newWi = initWi;
            int newHe = initHe;

            if (initWi > maxWi || initHe > maxHe) {
                float factor = 1f;
                if ((float)maxWi / (float)initWi < (float)maxHe / (float)initHe) {
                    factor = (float)maxWi / (float)initWi;
                } else {
                    factor = (float)maxHe / (float)initHe;
                }
                newWi = (int) Math.round((float)initWi * factor);
                newHe = (int) Math.round((float)initHe * factor);
            }

            BufferedImage bimage = new BufferedImage(newWi, newHe, BufferedImage.TYPE_INT_RGB);
            
            /*if(Utils.getExtension(remove).equalsIgnoreCase("png")||Utils.getExtension(remove).equalsIgnoreCase("gif"))
                bimage = new BufferedImage(newWi, newHe, BufferedImage.TYPE_INT_ARGB);*/

            Graphics2D g = bimage.createGraphics();
            
            //background color
            g.setBackground(new Color(255, 255, 255));

            Object interpolating = RenderingHints.VALUE_INTERPOLATION_BICUBIC;
            Object rendering = RenderingHints.VALUE_RENDER_QUALITY;
            Object colorRendering = RenderingHints.VALUE_COLOR_RENDER_QUALITY;
            Object antialiasing = RenderingHints.VALUE_ANTIALIAS_ON;
            Object dithering = RenderingHints.VALUE_DITHER_ENABLE;

            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolating);
            g.setRenderingHint(RenderingHints.KEY_RENDERING, rendering);
            g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, colorRendering);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasing);
            g.setRenderingHint(RenderingHints.KEY_DITHERING, dithering);
            Image scale;
            if ((newWi < 300) || (newHe < 300)) {
                scale = bufImage.getScaledInstance(newWi, newHe, 16);
            } else {
                scale = bufImage.getScaledInstance(newWi, newHe, 4);
            }
            g.drawImage(scale, 0, 0, new Color(255, 255, 255), null);
            
            return bimage;

        
    }
    
}
